/**
 * User: 蕨菜
 * Date: 2019-05-22
 * Time: 14:51
 * Description: 此文件简要说明
 */

const {
    Class,
    Grade,
    Student,
    Teacher
} = require('../../models');

const {
    AppUtil
} = require('../../util');

module.exports = async function addClass(body, ctx) {

    const {
        name,
        active,
        // 绑定的
        gradeYear: year,
        studentIds,
        teacherIds,
    } = body;

    const classInstance = await Class.create({
        name,
        active
    });

    if (!AppUtil.isEmpty(year)) {
        const gradeInstance = await Grade.findOne({
            where: {
                year
            }
        })
        await classInstance.addGrade(gradeInstance);
    }

    if (!AppUtil.isEmpty(studentIds)) {
        await classInstance.addStudents(...studentIds);
    }

    if (!AppUtil.isEmpty(teacherIds)) {
        await classInstance.addTeachers(...teacherIds);
    }

    const data = await Class.findByPk(classInstance.id);

    return ctx.body = {
        success: true,
        data
    }
}